<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>车站管理 - 列车车次管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="/css/admin.css">
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <!-- 侧边栏 -->
        <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">            <div class="position-sticky pt-3">
                <div class="text-center mb-4">
                    <img src="/images/logo.jpeg" alt="Logo" class="sidebar-logo">
                    <h4>列车车次管理系统</h4>
                    <h6 class="text-muted">管理员控制台</h6>
                </div>
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/dashboard.html">
                            <i class="bi bi-speedometer2 me-2"></i>
                            仪表盘
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/users.html">
                            <i class="bi bi-people me-2"></i>
                            用户管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/trains.html">
                            <i class="bi bi-train-front me-2"></i>
                            列车管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/admin/stations.html">
                            <i class="bi bi-building me-2"></i>
                            车站管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/routes.html">
                            <i class="bi bi-map me-2"></i>
                            路线管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/schedules.html">
                            <i class="bi bi-calendar-date me-2"></i>
                            时刻表管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/tickets.html">
                            <i class="bi bi-ticket-perforated me-2"></i>
                            票务管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/">
                            <i class="bi bi-house-door me-2"></i>
                            返回前台
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" id="logoutBtn">
                            <i class="bi bi-box-arrow-right me-2"></i>
                            退出登录
                        </a>
                    </li>
                </ul>
            </div>
        </nav>

        <!-- 主内容区 -->
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">车站管理</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <div class="btn-group me-2">
                        <button type="button" class="btn btn-sm btn-outline-secondary" id="refreshBtn">
                            <i class="bi bi-arrow-clockwise me-1"></i>刷新
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-secondary" id="exportBtn">
                            <i class="bi bi-download me-1"></i>导出
                        </button>
                    </div>
                    <button type="button" class="btn btn-sm btn-primary" id="addStationBtn">
                        <i class="bi bi-plus-circle me-1"></i>添加车站
                    </button>
                </div>
            </div>

            <!-- 搜索和筛选 -->
            <div class="card mb-4">
                <div class="card-body">
                    <form id="searchForm" class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label">车站名称</label>
                            <input type="text" class="form-control" id="searchStationName" placeholder="输入车站名称">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">车站代码</label>
                            <input type="text" class="form-control" id="searchStationCode" placeholder="输入车站代码">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">&nbsp;</label>
                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary">
                                    <i class="bi bi-search me-1"></i>搜索
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 车站列表 -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">车站列表</h5>
                </div>
                <div class="card-body">
                    <div id="loadingArea" class="text-center py-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2">正在加载车站数据...</p>
                    </div>

                    <div id="stationsArea" class="d-none">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                <tr>
                                    <th>车站ID</th>
                                    <th>车站名称</th>
                                    <th>车站代码</th>
                                    <th>所在城市</th>
                                    <th>省份</th>
                                    <th>等级</th>
                                    <th>电话</th>
                                    <th>地址</th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody id="stationsTable">
                                <!-- 动态加载车站数据 -->
                                </tbody>
                            </table>
                        </div>

                        <!-- 分页 -->
                        <nav aria-label="车站列表分页">
                            <ul class="pagination justify-content-center" id="pagination">
                                <!-- 动态生成分页 -->
                            </ul>
                        </nav>
                    </div>

                    <div id="noStationsArea" class="text-center py-5 d-none">
                        <i class="bi bi-building" style="font-size: 4rem; color: #dee2e6;"></i>
                        <h5 class="text-muted mt-3">暂无车站数据</h5>
                        <p class="text-muted">系统中还没有车站信息</p>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- 添加/编辑车站模态框 -->
<div class="modal fade" id="stationModal" tabindex="-1" aria-labelledby="stationModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="stationModalLabel">添加车站</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="stationForm">
                    <input type="hidden" id="stationId">
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="stationName" class="form-label">车站名称 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="stationName" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="stationCode" class="form-label">车站代码 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="stationCode" required>
                                <div class="form-text">例如：BJN（北京南）</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="cityName" class="form-label">所在城市 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="cityName" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="provinceName" class="form-label">省份 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="provinceName" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="stationLevel" class="form-label">车站等级</label>
                        <select class="form-select" id="stationLevel">
                            <option value="特等站">特等站</option>
                            <option value="一等站">一等站</option>
                            <option value="二等站">二等站</option>
                            <option value="三等站">三等站</option>
                            <option value="四等站">四等站</option>
                            <option value="五等站">五等站</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label for="phone" class="form-label">联系电话</label>
                        <input type="tel" class="form-control" id="phone">
                    </div>
                    
                    <div class="mb-3">
                        <label for="address" class="form-label">详细地址</label>
                        <textarea class="form-control" id="address" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveStationBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 确认删除模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>您确定要删除车站 <strong id="deleteStationName"></strong> 吗？</p>
                <p class="text-danger">此操作不可撤销！删除车站可能会影响相关的路线和时刻表！</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确认删除</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="/js/admin.js"></script>
<script>
    let allStations = [];
    let filteredStations = [];
    let currentPage = 1;
    let stationsPerPage = 10;
    let currentEditingStationId = null;

    $(document).ready(function() {
        // 检查管理员权限
        checkAdminPermission();
        
        // 加载车站数据
        loadStations();

        // 搜索表单提交
        $('#searchForm').on('submit', function(e) {
            e.preventDefault();
            filterStations();
        });

        // 刷新按钮
        $('#refreshBtn').on('click', function() {
            loadStations();
        });

        // 添加车站按钮
        $('#addStationBtn').on('click', function() {
            openStationModal();
        });

        // 保存车站
        $('#saveStationBtn').on('click', function() {
            saveStation();
        });

        // 确认删除
        $('#confirmDeleteBtn').on('click', function() {
            if (currentEditingStationId) {
                deleteStation(currentEditingStationId);
            }
        });

        // 退出登录
        $('#logoutBtn').on('click', function(e) {
            e.preventDefault();
            $.ajax({
                url: '/logout',
                type: 'POST',
                success: function() {
                    window.location.href = '/custom-login';
                }
            });
        });

        // 导出按钮
        $('#exportBtn').on('click', function() {
            exportStations();
        });
    });

    // 检查管理员权限
    function checkAdminPermission() {
        $.ajax({
            url: '/api/users/current',
            type: 'GET',
            success: function(user) {
                if (user.userRole !== 'ADMIN') {
                    alert('您没有访问管理后台的权限');
                    window.location.href = '/';
                }
            },
            error: function() {
                alert('请先登录');
                window.location.href = '/custom-login?redirect=' + encodeURIComponent(window.location.href);
            }
        });
    }

    // 加载车站数据
    function loadStations() {
        $('#loadingArea').removeClass('d-none');
        $('#stationsArea').addClass('d-none');
        $('#noStationsArea').addClass('d-none');

        $.ajax({
            url: '/api/stations',
            type: 'GET',
            success: function(stations) {
                allStations = stations;
                filteredStations = stations;
                
                $('#loadingArea').addClass('d-none');
                
                if (stations.length === 0) {
                    $('#noStationsArea').removeClass('d-none');
                } else {
                    renderStationsTable();
                    $('#stationsArea').removeClass('d-none');
                }
            },
            error: function(xhr) {
                $('#loadingArea').addClass('d-none');
                alert('加载车站数据失败: ' + (xhr.responseText || '请稍后重试'));
            }
        });
    }

    // 筛选车站
    function filterStations() {
        const stationName = $('#searchStationName').val().toLowerCase();
        const stationCode = $('#searchStationCode').val().toLowerCase();

        filteredStations = allStations.filter(station => {
            return (!stationName || station.stationName.toLowerCase().includes(stationName)) &&
                   (!stationCode || (station.stationCode && station.stationCode.toLowerCase().includes(stationCode)));
        });

        currentPage = 1;
        renderStationsTable();
    }

    // 渲染车站表格
    function renderStationsTable() {
        const startIndex = (currentPage - 1) * stationsPerPage;
        const endIndex = startIndex + stationsPerPage;
        const pageStations = filteredStations.slice(startIndex, endIndex);

        let tableHtml = '';
        pageStations.forEach(station => {
            tableHtml += `
                <tr>
                    <td>${station.id}</td>
                    <td><strong>${station.stationName}</strong></td>
                    <td><span class="badge bg-primary">${station.stationCode || 'N/A'}</span></td>
                    <td>${station.cityName || 'N/A'}</td>
                    <td>${station.provinceName || 'N/A'}</td>
                    <td>${getStationLevelBadge(station.stationLevel)}</td>
                    <td>${station.phone || 'N/A'}</td>
                    <td title="${station.address || 'N/A'}">${truncateText(station.address, 30)}</td>
                    <td>
                        <button class="btn btn-outline-primary btn-sm me-1" onclick="editStation(${station.id})" title="编辑">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-outline-danger btn-sm" onclick="showDeleteModal(${station.id}, '${station.stationName}')" title="删除">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
        });

        $('#stationsTable').html(tableHtml);
        renderPagination();
    }

    // 渲染分页
    function renderPagination() {
        const totalPages = Math.ceil(filteredStations.length / stationsPerPage);
        let paginationHtml = '';

        // 上一页
        if (currentPage > 1) {
            paginationHtml += `<li class="page-item"><a class="page-link" href="#" onclick="changePage(${currentPage - 1})">上一页</a></li>`;
        }

        // 页码
        for (let i = 1; i <= totalPages; i++) {
            if (i === currentPage) {
                paginationHtml += `<li class="page-item active"><a class="page-link" href="#">${i}</a></li>`;
            } else if (Math.abs(i - currentPage) <= 2 || i === 1 || i === totalPages) {
                paginationHtml += `<li class="page-item"><a class="page-link" href="#" onclick="changePage(${i})">${i}</a></li>`;
            } else if (Math.abs(i - currentPage) === 3) {
                paginationHtml += `<li class="page-item disabled"><a class="page-link" href="#">...</a></li>`;
            }
        }

        // 下一页
        if (currentPage < totalPages) {
            paginationHtml += `<li class="page-item"><a class="page-link" href="#" onclick="changePage(${currentPage + 1})">下一页</a></li>`;
        }

        $('#pagination').html(paginationHtml);
    }

    // 切换页面
    function changePage(page) {
        currentPage = page;
        renderStationsTable();
    }

    // 打开车站模态框
    function openStationModal(station = null) {
        currentEditingStationId = station ? station.id : null;
        
        if (station) {
            $('#stationModalLabel').text('编辑车站');
            $('#stationId').val(station.id);
            $('#stationName').val(station.stationName);
            $('#stationCode').val(station.stationCode);
            $('#cityName').val(station.cityName);
            $('#provinceName').val(station.provinceName);
            $('#stationLevel').val(station.stationLevel);
            $('#phone').val(station.phone);
            $('#address').val(station.address);
        } else {
            $('#stationModalLabel').text('添加车站');
            $('#stationForm')[0].reset();
        }
        
        $('#stationModal').modal('show');
    }

    // 编辑车站
    function editStation(stationId) {
        const station = allStations.find(s => s.id === stationId);
        if (station) {
            openStationModal(station);
        }
    }

    // 保存车站
    function saveStation() {
        if (!$('#stationForm')[0].checkValidity()) {
            $('#stationForm').addClass('was-validated');
            return;
        }

        const stationData = {
            stationName: $('#stationName').val(),
            stationCode: $('#stationCode').val(),
            cityName: $('#cityName').val(),
            provinceName: $('#provinceName').val(),
            stationLevel: $('#stationLevel').val(),
            phone: $('#phone').val(),
            address: $('#address').val()
        };

        const url = currentEditingStationId ? `/api/stations/${currentEditingStationId}` : '/api/stations';
        const method = currentEditingStationId ? 'PUT' : 'POST';

        $.ajax({
            url: url,
            type: method,
            contentType: 'application/json',
            data: JSON.stringify(stationData),
            success: function() {
                $('#stationModal').modal('hide');
                alert(currentEditingStationId ? '车站更新成功' : '车站添加成功');
                loadStations();
            },
            error: function(xhr) {
                alert('保存失败: ' + (xhr.responseText || '请稍后重试'));
            }
        });
    }

    // 显示删除确认模态框
    function showDeleteModal(stationId, stationName) {
        currentEditingStationId = stationId;
        $('#deleteStationName').text(stationName);
        $('#deleteModal').modal('show');
    }

    // 删除车站
    function deleteStation(stationId) {
        $.ajax({
            url: `/api/stations/${stationId}`,
            type: 'DELETE',
            success: function() {
                $('#deleteModal').modal('hide');
                alert('车站删除成功');
                loadStations();
            },
            error: function(xhr) {
                alert('删除失败: ' + (xhr.responseText || '请稍后重试'));
            }
        });
    }

    // 导出车站数据
    function exportStations() {
        const csvContent = generateCSV(filteredStations);
        downloadCSV(csvContent, 'stations.csv');
    }

    // 生成CSV内容
    function generateCSV(stations) {
        const headers = ['车站ID', '车站名称', '车站代码', '所在城市', '省份', '等级', '电话', '地址'];
        let csvContent = headers.join(',') + '\n';
        
        stations.forEach(station => {
            const row = [
                station.id,
                station.stationName,
                station.stationCode || '',
                station.cityName || '',
                station.provinceName || '',
                station.stationLevel || '',
                station.phone || '',
                station.address || ''
            ];
            csvContent += row.join(',') + '\n';
        });
        
        return csvContent;
    }

    // 下载CSV文件
    function downloadCSV(content, filename) {
        const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = filename;
        link.click();
    }

    // 工具函数
    function getStationLevelBadge(level) {
        if (!level) return '<span class="badge bg-secondary">未设置</span>';
        
        const levelColors = {
            '特等站': 'danger',
            '一等站': 'warning',
            '二等站': 'info',
            '三等站': 'primary',
            '四等站': 'success',
            '五等站': 'secondary'
        };
        
        const color = levelColors[level] || 'secondary';
        return `<span class="badge bg-${color}">${level}</span>`;
    }

    function truncateText(text, maxLength) {
        if (!text) return 'N/A';
        if (text.length <= maxLength) return text;
        return text.substring(0, maxLength) + '...';
    }
</script>
</body>
</html>
